package com.caigou.modules.info.respository

import com.caigou.comm.base.bean.HttpResult
import com.caigou.modules.info.bean.InfoBean
import com.caigou.modules.info.network.HttpInfoService
import dagger.hilt.android.scopes.ActivityRetainedScoped
import kotlinx.coroutines.flow.Flow
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.File
import javax.inject.Inject

/**
 * @author #Suyghur.
 * Created on 2021/09/23
 */
@ActivityRetainedScoped
class InfoRepository @Inject constructor() {

    fun getArticleList(page: Int, limit: Int, userId: String, sort: Int, type: Int): Flow<HttpResult<InfoBean>> {
        return HttpInfoService.service.getArticleList(page, limit, userId, sort, type)
    }

    fun getMyInfoList(page: Int, limit: Int, userId: String, checkStatus: Int = 0): Flow<HttpResult<InfoBean>> {
        return HttpInfoService.service.getMyInfoList(page, limit, userId, checkStatus)
    }

    fun getMyCollectedList(page: Int, limit: Int, userId: String): Flow<HttpResult<InfoBean>> {
        return HttpInfoService.service.getMyCollectedList(page, limit, userId)
    }

    fun publishInfo(cover: File, files: MutableList<File>, title: String, content: String, userId: String, type: Int): Flow<HttpResult<String>> {
        val body = MultipartBody.Builder()
            .addFormDataPart("title", title)
            .addFormDataPart("content", content)
            .addFormDataPart("userId", userId)
            .addFormDataPart("type", type.toString())
        val coverBody = cover.asRequestBody("MultipartFile".toMediaTypeOrNull())
        body.addFormDataPart("cover", cover.name, coverBody)
        files.forEach {
            val fileBody = it.asRequestBody("MultipartFile".toMediaTypeOrNull())
            body.addFormDataPart("files", it.name, fileBody)
        }
        return HttpInfoService.service.publishInfo(body.build())
    }

    fun setInfoLike(dataId: Int, senderId: String, receiverId: String): Flow<HttpResult<String>> {
        val jsonObject = JSONObject()
        jsonObject.put("dataId", dataId)
        jsonObject.put("senderId", senderId)
        jsonObject.put("receiverId", receiverId)
        val body = jsonObject.toString().toRequestBody()
        return HttpInfoService.service.setInfoLike(body)
    }
}